package com.nfit.seckilldemo1.service.impl;

import com.nfit.seckilldemo1.config.RabbitMQConfig;
import com.nfit.seckilldemo1.pojo.SeckillOrderMessage;
import com.nfit.seckilldemo1.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

/**
 * ClassName:OrderConsumer
 * Package:com.nfit.seckilldemo1.service
 * Description
 *
 * @Author L
 * @Create 2025/2/17 19:47
 */
@Component
public class OrderConsumer {

    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RabbitListener(queues = RabbitMQConfig.ORDER_QUEUE)
    @Transactional(rollbackFor = Exception.class)
    public void processOrder(SeckillOrderMessage message, Channel channel,
                             @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        try {
            orderService.createOrder(message);
            channel.basicAck(tag, false); // 手动确认消息
        } catch (Exception e) {
            // 回滚Redis库存
            String stockKey = "seckill:stock:" + message.getSkuId();
            redisTemplate.opsForValue().increment(stockKey, message.getQuantity());
            // 消息重试或进入死信队列
            channel.basicNack(tag, false, true);
        }
    }
}


